//
//  HCMindHeadViewController.m
//  HappyChildren
//
//  Created by WillyZhao on 2017/1/2.
//  Copyright © 2017年 WillyZhao. All rights reserved.
//

#import "HCMindHeadViewController.h"

#import "HCMineHeadTableViewCell.h"

#import "ImageUploadTools.h"
#import "ZFActionSheet.h"
#import "WayImagePicker.h"

#import "HCMineMsgModel.h"
#import "AppDelegate.h"
#import "HCLogViewController.h"

@interface HCMindHeadViewController () <UITableViewDelegate,ZFActionSheetDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate> {
    UITableView *tabloeView_;
    UIScrollView *scrollView_;
    UIButton *button;
    MBProgressHUD *hud_hc;
    HCMineMsgModel *mineModel;
    UIImageView *image11;
    AppDelegate *appDelegate;
    HCPopLoadingView *popLoading;
    UILabel *name_label;
}

@end

@implementation HCMindHeadViewController

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

//    if (![PublicFunction isNull:HCGETUSER(@"userid")]) {
        self.dataRequest.delegate = self;
        [self.dataRequest postHC_MineAbout:HCGETUSER(@"userid")];
//    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    

    
    //通知栏初始化
    self.textTitle = @"账户设置";
    popLoading = [[HCPopLoadingView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [popLoading showAnimate];

    
    self.centerView.frame = CGRectMake(self.centerView.frame.origin.x, self.centerView.frame.origin.y, self.centerView.frame.size.width, self.centerView.frame.size.height+49);
    
    [self setLeftButtonImage:@"happy_mine_LBackIMG"];
    
    
    //视图初始化
    [self loadAllSubViews];
    
    //添加观察者
    [tabloeView_ addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:@"frame"];
    
    // Do any additional setup after loading the view.
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"contentSize"]) {
        CGSize size;
        [change[@"new"] getValue:&size];
        tabloeView_.frame = CGRectMake(tabloeView_.frame.origin.x, tabloeView_.frame.origin.y, tabloeView_.frame.size.width, size.height);
        button.frame = CGRectMake(button.frame.origin.x, tabloeView_.frame.origin.y+tabloeView_.frame.size.height+10, button.frame.size.width, button.frame.size.height);
        scrollView_.contentSize = CGSizeMake(scrollView_.frame.size.width, button.frame.size.height+button.frame.origin.y+10);
    }
}

-(void)loadAllSubViews {
    
    scrollView_ = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.centerView.frame.size.width, self.centerView.frame.size.height-49)];
    scrollView_.showsVerticalScrollIndicator = NO;
    [self.centerView addSubview:scrollView_];
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"happy_mine_headIMG_D"]];
    imageView.frame = CGRectMake(0, 0, self.centerView.frame.size.width, YBKAdaptiveH(118));
    imageView.userInteractionEnabled = YES;
    [scrollView_ addSubview:imageView];
    
    image11 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"happy_mine_headerIMG"]];
    image11.frame = CGRectMake((imageView.frame.size.width - YBKAdaptiveW(61))/2.0, (imageView.frame.size.height - YBKAdaptiveW(61))/2.0-YBKAdaptiveH(10), YBKAdaptiveW(61), YBKAdaptiveW(61));
    image11.userInteractionEnabled = YES;
    image11.layer.masksToBounds = YES;
    image11.layer.cornerRadius = YBKAdaptiveW(61)/2.0;
    image11.contentMode = UIViewContentModeScaleAspectFill;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageUpload:)];
    [image11 addGestureRecognizer:tap];
    
    [imageView addSubview:image11];
    
    name_label = [[UILabel alloc] initWithFrame:CGRectMake(0, imageView.frame.size.height - YBKAdaptiveH(10)-image11.frame.origin.y, self.centerView.frame.size.width, 15)];
    name_label.text = @"更换头像";
    name_label.font = YBKSystemFont(YBKAdaptiveFont(11));
    name_label.textAlignment = NSTextAlignmentCenter;
    name_label.textColor = [UIColor whiteColor];
    [imageView addSubview:name_label];
    
    tabloeView_ = [[UITableView alloc] initWithFrame:CGRectMake(0, imageView.frame.origin.y+imageView.frame.size.height, self.centerView.frame.size.width, 44*5+20)];
    tabloeView_.delegate = self;
    tabloeView_.dataSource = self;
    tabloeView_.scrollEnabled = NO;
    tabloeView_.separatorStyle = UITableViewCellSeparatorStyleNone;
    [scrollView_ addSubview:tabloeView_];
    
    [tabloeView_ registerNib:[UINib nibWithNibName:@"HCMineHeadTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"cellHead"];
    
    button = [[UIButton alloc] initWithFrame:CGRectMake(5, tabloeView_.frame.origin.y+tabloeView_.frame.size.height+10, (self.centerView.frame.size.width - 10), 40)];
    button.layer.cornerRadius = 5.0f;
    [button setTitle:@"退出" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(logOutBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    button.backgroundColor = YBKRGBCOLOR(240, 96, 96, 1);
    [scrollView_ addSubview:button];
    
//    appDelegate =  (AppDelegate *)[UIApplication sharedApplication].delegate;
//    appDelegate.rootVC.tabBarView.hidden = YES;
//    [self.view bringSubviewToFront:button];
    
}

//-(void)mainBtnAction:(UIButton *)mainBtn {
//    if (mainBtn.tag == 0) {
//        [self.navigationController popViewControllerAnimated:YBKAnimation];
//        appDelegate.rootVC.tabBarView.hidden = NO;
//    }else if (mainBtn.tag == 1) {
//        [self rightBtnAction:mainBtn];
//    }
//}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"点击开始");
}

-(void)logOutBtnAction:(UIButton *)btn {
    NSLog(@"退出");
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userid"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"hcphone"];
    HCLogViewController *log = [[HCLogViewController alloc] init];
    
    UINavigationController *na = [[UINavigationController alloc] initWithRootViewController:log];
    na.navigationBarHidden = YES;
    [self.navigationController presentViewController:na animated:YES completion:nil];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

-(BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 0) {
        return YES;
    }else{
        if (indexPath.section == 3) {
            return YES;
        }else{
            return NO;
        }
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 2;
    }else if (section == 1) {
        return 1;
    }else if(section == 2){
        return 2;
    }else{
        return 1;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HCMineHeadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellHead" forIndexPath:indexPath];
    [cell cellModel:indexPath dataModel:mineModel];

    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    }else{
        return 10;
    }
}


-(void)actionSheetWillDismiss:(BOOL)isShow {
    NSLog(@"隐藏");
}

-(void)imageUpload:(UITapGestureRecognizer *)tap {
    NSLog(@"图片点击");
    ZFActionSheet *actionSheet = [ZFActionSheet actionSheetWithTitle:nil confirms:@[@"拍照",@"本地上传"] cancel:@"取消" style:ZFActionSheetStyleCancel];
    actionSheet.delegate = self;
    [actionSheet showInView:self.view.window];
}



- (void)clickAction:(ZFActionSheet *)actionSheet atIndex:(NSUInteger)index {
    WayImagePicker *picker = [[WayImagePicker alloc] init];
    __block __weak HCMindHeadViewController  *weakSelf = self;
    [picker initializeImagePickerWith:index AndBlock:^(NSInteger index) {
        UIImagePickerController *imageController = [[UIImagePickerController alloc] init];
        imageController.delegate = weakSelf;
        imageController.allowsEditing = YES;
        imageController.sourceType = index;
        [weakSelf presentViewController:imageController animated:YES completion:nil];
    }];

}
#pragma mark - 图片保存到本地沙盒
-(void)saveImage:(UIImage *)currentImage withName:(NSString *)imageNames {
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 1);   //1为不缩放保存
    //获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageNames];
    //将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
}


#pragma mark - 获取图片缓存并显示
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    //
    
    //保存图片致本地，上传图片到服务器需要使用
    [self saveImage:image withName:@"avatar.png"];
    
    //    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"avatar.png"];
    
    //    UIImage *savedImage = [[UIImage alloc] initWithContentsOfFile:fullPath];
    
    //TODO  设置图片显示
    
    
    NSData *data_image = UIImageJPEGRepresentation(image, 0.5);
    
    NSString *image_text_time = [PublicFunction getDatetimestamp111];
    
    __block __weak NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    
//    hud_hc = [MBProgressHUD showHUDAddedTo:centerView animated:YES];
//    hud_hc.labelText = @"图片上传中,请稍后...";
    [popLoading showAnimate];

    [ImageUploadTools defaultManmagerWith:data_image andtime:image_text_time AndBlock:^(NSDictionary *str) {
        [popLoading hidden];
        dic = (NSMutableDictionary *) str;
        if ([dic[@"stat"] integerValue] != 200) {
            [XHToast showBottomWithText:@"头像上传失败"];
        }else{
            [XHToast showBottomWithText:@"头像上传成功"];
            image11.image = image;
        }
        
    }];
    
    
    
}

-(void)dataRequesterFinish:(DataRequester *)requester requesterWithType:(DataRequestType)aType receiveDictionary:(NSDictionary *)dictionary {
    NSLog(@"个人资料请求成功:%@",dictionary);
    [popLoading hidden];
    mineModel = [[HCMineMsgModel alloc] initWithDictionary:dictionary error:nil];
    if ([PublicFunction isNull:mineModel.path]) {
        image11.image = [UIImage imageNamed:@"happy_mine_headerIMG"];
    }else{
        if ([[NSString stringWithFormat:@"%@",mineModel.path] isEqualToString:@"http://www.cdjiayibai.com"]) {
            image11.image = [UIImage imageNamed:@"happy_mine_headerIMG"];
        }else{
            [image11 sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",mineModel.path]]];
        }
    }
    name_label.text = [NSString stringWithFormat:@"%@",mineModel.name];
    [tabloeView_ reloadData];
}

-(void)dataRequesterFail:(DataRequester *)requester requesterWithType:(DataRequestType)aType receiveErrorDictionary:(NSDictionary *)dictionary {
    NSLog(@"个人资料请求失败");
    [popLoading hidden];
    [XHToast showBottomWithText:@"网络请求失败"];
}
-(void)dealloc {
    [tabloeView_ removeObserver:self forKeyPath:@"contentSize"];
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            [self pushChildrenViewController:@"HCMineNameViewController" parameterObject:nil dataObject:nil];
        }
    }else{
        [self pushChildrenViewController:@"HCRePwdViewController" parameterObject:nil dataObject:nil];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
